package cn.samler.shopapi.Controller;

import cn.samler.shopapi.Entity.User;
import cn.samler.shopapi.Model.Request.Cart.Goods;
import cn.samler.shopapi.Model.Request.Cart.CartModel;
import cn.samler.shopapi.Model.Sys.Response;
import cn.samler.shopapi.Model.Sys.ServiceResult;
import cn.samler.shopapi.Service.CartService;
import com.alibaba.fastjson.JSONObject;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;

@RestController
@RequestMapping("/cart")
public class CartController {
    private CartService cartService;

    CartController(CartService cartService) {
        this.cartService = cartService;
    }

    /**
     * 获取购物车列表
     *
     * @return List<Cart>
     */
    @GetMapping("list")
    public Response list(HttpServletRequest request) {
        return Response.success(cartService.findAll(((User) request.getAttribute("current_user")).getId()));
    }

    /**
     * 往购物车添加一个商品
     *
     * @param request
     * @param goods
     * @return success or failure
     */
    @PostMapping("add")
    public Response add(HttpServletRequest request, @RequestBody Goods goods) {
        ServiceResult result = cartService.add(((User) request.getAttribute("current_user")).getId(), goods);
        if (result.isSuccess())
            return Response.success();

        return Response.failure(result.getData());
    }

    @PostMapping("update_number")
    public Response updateNumber(HttpServletRequest request, @RequestBody CartModel cartModel) {
        ServiceResult result = cartService.updateNumber((User) request.getAttribute("current_user"), cartModel);
        if (result.isSuccess())
            return Response.success();

        return Response.failure(result.getData());
    }

    /**
     * 删除购物车中的一件商品
     *
     * @param request
     * @param cartModel
     * @return success or failure
     */
    @PostMapping("delete")
    public Response remove(HttpServletRequest request, @RequestBody List<CartModel> cartModel) {
        int uid = ((User) request.getAttribute("current_user")).getId();
        cartModel.forEach(item -> {
            cartService.removeByToken(uid, item.getGid(), item.getSpecToken());
        });

        return Response.success();
    }

    /**
     * 更新购物车中的一件商品
     *
     * @param request
     * @param goods
     * @return success or failure
     */
    @PostMapping("update")
    public Response update(HttpServletRequest request, @RequestBody Goods goods) {
        if (cartService.update(((User) request.getAttribute("current_user")).getId(), goods))
            return Response.success();
        return Response.failure("更新失败");
    }
}
